import 'package:merchants/models/merchant.dart';
import 'package:merchants/services/base-service.dart';

class MerchantService extends BaseService {
  MerchantService({required super.ref});
  Future<List<Merchant>> fetchMerchants({String? keyword}) async {
    try {
      // 新后端接口：/merchants/all，直接返回 List<MerchantJson>
      final response = await get<List<dynamic>>(
        '/merchants/all',
        requireToken: false,
        parser: (json) => json['data'] as List<dynamic>? ?? [],
      );

      final list = response
          .map((item) => Merchant.fromJson(item as Map<String, dynamic>))
          .toList();

      if (keyword != null && keyword.isNotEmpty) {
        final lower = keyword.toLowerCase();
        return list.where((m) {
          return m.name.toLowerCase().contains(lower) ||
              (m.miniProgramName.toLowerCase().contains(lower)) ||
              (m.legalPersonName.toLowerCase().contains(lower));
        }).toList();
      }

      return list;
    } catch (e) {
      throw ApiException('获取商户列表失败: $e');
    }
  }

  Future<Merchant> getMerchantById(String id) async {
    try {
      final response = await post<Map<String, dynamic>>(
        '/merchant/get',
        body: {
          'filter': {
            'where': {
              '_id': {'\$eq': id},
            },
          },
        },
        parser: (json) {
          if (json['success'] != true) {
            throw ApiException(json['message'] ?? '查询商户失败');
          }
          return json;
        },
        requireToken: false,
      );

      if (response['data'] != null) {
        return Merchant.fromJson(response['data']);
      } else {
        throw ApiException('商户未找到');
      }
    } catch (e) {
      throw ApiException('获取商户失败: $e');
    }
  }

  // 创建商户
  Future<String> createMerchant(Merchant merchant) async {
    try {
      final response = await post<Map<String, dynamic>>(
        '/merchant/create',
        body: {'data': merchant.toJson()},
        parser: (json) {
          if (json['statusCode'] != 200) {
            throw ApiException(
              json['message'] ?? '创建商户失败',
              statusCode: json['statusCode'] as int?,
            );
          }
          return json;
        },
      );
      return response['data']['id'] as String;
    } catch (e) {
      throw ApiException('创建商户失败: $e');
    }
  }

  // 更新商户
  Future<Merchant> updateMerchant(String id, Merchant merchant) async {
    try {
      // 过滤掉不可更新的字段（例如 createdAt、union_id 等）
      final merchantData =
          merchant.toJson()
            ..remove('createdAt') // 不允许修改创建时间
            ..remove('union_id') // 不允许修改 union_id
            ..remove('merchantId') // 不允许修改 merchantId
            ..['updatedAt'] = DateTime.now().millisecondsSinceEpoch; // 更新时间

      final response = await post<Map<String, dynamic>>(
        '/merchant/update',
        body: {'id': id, 'data': merchantData},
        parser: (json) {
          if (json['success'] != true) {
            throw ApiException(
              json['message'] ?? '更新商户失败',
              statusCode: json['statusCode'] as int?,
            );
          }
          return json;
        },
      );

      // 后端返回的 data 应该是更新后的商户数据
      final updatedMerchant = response['data'] as Map<String, dynamic>;
      return Merchant.fromJson(updatedMerchant);
    } catch (e) {
      throw ApiException('更新商户失败: $e');
    }
  }

  // 删除商户
  Future<void> deleteMerchant(String? id) async {
    try {
      await post<Map<String, dynamic>>(
        '/merchant/delete',
        queryParams: {'id': id},
        parser: (json) {
          if (json['statusCode'] != 200) {
            throw ApiException(
              json['message'] ?? '删除商户失败',
              statusCode: json['statusCode'] as int?,
            );
          }
          return json;
        },
      );
    } catch (e) {
      throw ApiException('删除商户失败: $e');
    }
  }

  // 检查用户是否绑定商户
  Future<Map<String, dynamic>> checkBinding(String unionId) async {
    try {
      // 步骤 1：查询 merchant_users 表
      final response = await post<Map<String, dynamic>>(
        '/merchant-user/get-list',
        body: {
          'filter': {
            'where': {
              'union_id': {'\$eq': unionId},
            },
          },
        },
        parser: (json) {
          if (json['statusCode'] != 200) {
            throw ApiException(
              json['message'] ?? '查询绑定信息失败',
              statusCode: json['statusCode'] as int?,
            );
          }
          return json;
        },
      );

      final List<dynamic> records =
          response['data']['records'] as List<dynamic>;
      if (records.isNotEmpty) {
        final record = records.first as Map<String, dynamic>;
        return {
          'hasMerchant': true,
          'merchantId': record['merchant_id'].toString(),
          'role': record['role'] as String,
        };
      }

      // 步骤 2：查询 merchants 表
      final merchantResponse = await post<Map<String, dynamic>>(
        '/merchant/get-list',
        body: {
          'filter': {
            'where': {
              'union_id': {'\$eq': unionId},
            },
          },
        },
        parser: (json) {
          if (json['statusCode'] != 200) {
            throw ApiException(
              json['message'] ?? '查询商户失败',
              statusCode: json['statusCode'] as int?,
            );
          }
          return json;
        },
      );

      final List<dynamic> merchantRecords =
          merchantResponse['data']['records'] as List<dynamic>;
      if (merchantRecords.isNotEmpty) {
        final merchant = merchantRecords.first as Map<String, dynamic>;
        return {
          'hasMerchant': true,
          'merchantId': merchant['id'].toString(),
          'role': 'admin',
        };
      }

      return {'hasMerchant': false};
    } catch (e) {
      throw ApiException('检查绑定信息失败: $e');
    }
  }

  // 申请加入商户
  Future<void> applyToJoinMerchant(
    String merchantId,
    String applicantName,
  ) async {
    try {
      await post<Map<String, dynamic>>(
        '/merchants/apply',
        body: {'merchantId': merchantId, 'applicantName': applicantName},
        parser: (json) {
          if (json['success'] != true) {
            throw ApiException(json['message'] ?? '申请失败');
          }
          return json;
        },
      );
    } catch (e) {
      throw ApiException('申请加入商户失败: $e');
    }
  }
}
